package com.example.send.config;

import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;

import java.util.Objects;

public class TraceableMessagePostProcessor implements MessagePostProcessor {

    public static final MessagePostProcessor INSTANCE = new TraceableMessagePostProcessor();

    @Override
    public Message postProcessMessage(Message message) {
        MessageProperties messageProperties = message.getMessageProperties();
        if (Objects.isNull(messageProperties)) {
            return this.createNewMessage(message);
        } else {
            this.addTraceId(messageProperties);
            return message;
        }
    }

    private Message createNewMessage(Message message) {
        MessageProperties messageProperties = new MessageProperties();
        this.addTraceId(messageProperties);
        return new Message(message.getBody(), messageProperties);
    }

    private void addTraceId(MessageProperties messageProperties) {
        messageProperties.getHeaders().put("swTraceId", TraceContext.traceId());
    }

    private TraceableMessagePostProcessor() {

    }



}
